import asyncio

__author__ = 'thanatos'

import time

from orm import Model, LongField, StringField, FloatField, BooleanField, Field, ModelField, TextField, MultiField


class User(Model):
    __table__ = 'User'

    id = LongField(primary_key=True)
    name = StringField()
    password = StringField()
    email = StringField(length=30)
    image = StringField(length=200, default='http://t11.baidu.com/it/u=2252020396,3421242360&fm=56')
    isAdmin = BooleanField(name='is_admin')
    create_at = FloatField(default=time.time())
    telephone = StringField(length=30)
    roles = MultiField('user_id', 'Role', another_key='role_id', table='User_Role')

    @asyncio.coroutine
    def access(self, name):
        """
        权限资源验证
        :param name:
        :return:
        """
        count = yield from User.count(self[User.__key__], name,
                                      sql='SELECT COUNT(*) AS count FROM User_Role_Privilege WHERE user_id=? AND privilege_resource=?')
        return bool(count)


class Blog(Model):
    __table__ = 'Blog'

    id = LongField(primary_key=True)
    title = StringField(length=50)
    content = TextField(name='content')
    user_id = LongField()
    create_at = FloatField(default=time.time())
    user = ModelField(name='user_id', model=User)


class Comment(Model):
    __table__ = 'Comment'

    id = LongField(primary_key=True)
    blog_id = LongField()
    user_id = LongField()
    content = TextField(name='content')
    create_time = FloatField(default=time.time())
    user = ModelField(name='user_id', model=User)
    blog = ModelField(name='blog_id', model=Blog)


class Role(Model):
    __table__ = 'Role'

    id = LongField(primary_key=True)
    name = StringField()
    description = StringField(length=255)
    privileges = MultiField('role_id', 'Privilege', another_key='privilege', table='Role_Privilege')


class Privilege(Model):
    __table__ = 'Privilege'

    id = LongField(primary_key=True)
    name = StringField()
    resource = StringField(length=50)
    url = StringField(length=150)
    is_display = BooleanField(default=True)
    description = StringField(length=255)
    parent = ModelField(name='parent_id', model='Privilege')

    @classmethod
    @asyncio.coroutine
    def find_children(cls, args):
        if isinstance(args, dict):
            children = yield from Privilege.findAll(args[cls.__key__], where='parent_id=?')
            if children:
                args.children = children
                yield from cls.find_children(children)
        if isinstance(args, list):
            for child in args:
                yield from cls.find_children(child)
